package matrix;

/*
 *@description 生命游戏
 *@author hkfan
 *@version 1.0
 *@create 2025/6/5 13:40
 */
public class LeetCode_289 {

    public void gameOfLife(int[][] board) {
        //1. 逐个赋值
        int m=board.length,n=board[0].length;
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                update(board,i,j);
            }
        }

        //2. 重新赋值
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (board[i][j]==-2 || board[i][j]==-4){
                    board[i][j]=1;
                }else {
                    board[i][j]=0;
                }
            }
        }
    }

    /**
     * @description 更新矩阵值（-1:0->0  -2:0->1 -3:1->0 -4:1->1）
     * @author hkfan
     * @time 2025/6/5 15:54
     */
    private void update(int[][] board, int i, int j) {
        int m=board.length,n=board[0].length;
        int res=0;
        if (i-1>=0 && j-1>=0){
            res+=(board[i-1][j-1]==-3 || board[i-1][j-1]==-4 ||board[i-1][j-1]==1)?1:0;
        }
        if (i-1>=0 ){
            res+=(board[i-1][j]==-3 || board[i-1][j]==-4 ||board[i-1][j]==1)?1:0;
        }
        if (j-1>=0){
            res+=(board[i][j-1]==-3 || board[i][j-1]==-4 ||board[i][j-1]==1)?1:0;
        }

        if (i+1<m && j+1<n){
            res+=(board[i+1][j+1]==-3 || board[i+1][j+1]==-4 ||board[i+1][j+1]==1)?1:0;
        }
        if (i+1<m ){
            res+=(board[i+1][j]==-3 || board[i+1][j]==-4 ||board[i+1][j]==1)?1:0;
        }
        if (j+1<n){
            res+=(board[i][j+1]==-3 || board[i][j+1]==-4 ||board[i][j+1]==1)?1:0;
        }

        if (i-1>=0 && j+1<n){
            res+=(board[i-1][j+1]==-3 || board[i-1][j+1]==-4 ||board[i-1][j+1]==1)?1:0;
        }
        if (i+1<m && j-1>=0){
            res+=(board[i+1][j-1]==-3 || board[i+1][j-1]==-4 ||board[i+1][j-1]==1)?1:0;
        }
        if (board[i][j]==1){    //存活
            if (res==2 ||res==3){
                board[i][j]=-4;
            }else {
                board[i][j]=-3;
            }
        }else {     //死亡
            if (res==3){
                board[i][j]=-2;
            }else {
                board[i][j]=-1;
            }
        }
    }


}
